import { ref } from "vue"
import store from "@/store"
import { defineStore } from "pinia"
import { type RouteRecordRaw } from "vue-router"
import { constantRoutes } from "@/router"
import { flatMultiLevelRoutes } from "@/router/helper"
import routeSettings from "@/config/route"

const Layouts = () => import("@/layouts/index.vue")

interface routeItem {
  name: string
  component: string | null | any
  meta: Object
  path: string
  title: string
  svgIcon: string
  hidden?: boolean
  children?: routeItem[] | any
}

const hasPermission = (roles: string[], route: RouteRecordRaw) => {
  const routeRoles = route.meta?.roles
  return routeRoles ? roles.some((role) => routeRoles.includes(role)) : true
}

const filterDynamicRoutes = (routes: RouteRecordRaw[], roles: string[]) => {
  const res: RouteRecordRaw[] = []
  routes.forEach((route) => {
    const tempRoute = { ...route }
    if (hasPermission(roles, tempRoute)) {
      if (tempRoute.children) {
        tempRoute.children = filterDynamicRoutes(tempRoute.children, roles)
      }
      res.push(tempRoute)
    }
  })
  return res
}

export const usePermissionStore = defineStore("permission", () => {
  // 用户信息返回的菜单
  const dynamicRoutes: [] = []

  /** 可访问的路由 */
  const routes = ref<RouteRecordRaw[]>(constantRoutes)
  /** 有访问权限的动态路由 */
    // const addRoutes = ref<RouteRecordRaw[]>([])
  const addRoutes = ref([])

  /** 根据角色生成可访问的 Routes（可访问的路由 = 常驻路由 + 有访问权限的动态路由） */
  const setRoutes = (roles: string[]) => {
    const accessedRoutes = filterDynamicRoutes(dynamicRoutes, roles)
    _set(accessedRoutes)
  }

  /** 所有路由 = 所有常驻路由 + 所有动态路由 */
  const setAllRoutes = (dynamicRoutes: []) => {
    _set(dynamicRoutes)
  }

  // : RouteRecordRaw[]
  const _set = (accessedRoutes: any) => {
    routes.value = constantRoutes.concat(accessedRoutes)
    addRoutes.value = routeSettings.thirdLevelRouteCache ? flatMultiLevelRoutes(accessedRoutes) : accessedRoutes
  }

  //  将 menus 菜单，转换为 route 路由数组
  const GenerateRoutes = (menus: routeItem[]) => {
    const asyncRouterMap = JSON.parse(JSON.stringify(menus))
    return asyncRouterMap.filter((route: routeItem) => {
      route.meta = {
        title: route.title,
        svgIcon: route.svgIcon,
        hidden: route.hidden
      }
      if (route.component) {
        // 当 import() 路径是一个带有变量的模版，
        // 1. 必须 带有文件后缀名
        // 3. 返回一个 Promise并将的组件作为value传入resolve component:() =>  Promise.resolve(your_component)
        // 所有导入（import）必须使用相对被导入文件的路径。导入**不允许以一个变量开头、使用绝对路径**,或者裸导入。
        const paths = route.component.split("/").filter((path: string) => path)

        let comp = null
        if (paths.length == 2) {
          comp = import(`../../views/${paths[0]}/${paths[1]}.vue`)
        }
        if (paths.length == 3) {
          comp = import(`../../views/${paths[0]}/${paths[1]}/${paths[2]}.vue`)
        }
        if (paths.length == 4) {
          comp = import(`../../views/${paths[0]}/${paths[1]}/${paths[2]}/${paths[3]}.vue`)
        }
        route.component = () => Promise.resolve(comp)
      } else {
        // null
        route.component = Layouts
      }
      if (route.children && route.children.length > 0) {
        route.children = GenerateRoutes(route.children)
      }
      return true
    })
  }

  return { routes, addRoutes, setRoutes, setAllRoutes, GenerateRoutes, dynamicRoutes }
})

/** 在 setup 外使用 */
export function usePermissionStoreHook() {
  return usePermissionStore(store)
}
